package com.papercut.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.papercut.purchase.PurchaseEntity;
import com.papercut.purchase.PurchaseItem;
 
import android.util.Log;
 
public class RestClient {
	
	private static String transactionUrl = "http://ec2-50-19-212-0.compute-1.amazonaws.com/index.php/bandaid/purchaseInfo";
	private static String createUrl = "http://ec2-50-19-212-0.compute-1.amazonaws.com/index.php/bandaid/createAccount";
	private static String authenticateUrl = "http://ec2-50-19-212-0.compute-1.amazonaws.com/index.php/bandaid/verifyAccount";
	private static String mtomUrl = "http://ec2-50-19-212-0.compute-1.amazonaws.com/index.php/bandaid/createMobileExchange";
	
	//private int HttpMethod;
	
	/*public RestClient(int HttpMethod) {
		this.HttpMethod = HttpMethod;
	}*/
 
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
 
    
    public static PurchaseEntity getTransaction (int transID) {
    	HttpClient httpclient = new DefaultHttpClient();
    	 
        // Prepare a request object
        HttpGet httpget = new HttpGet(transactionUrl); 
        httpget.addHeader(new BasicHeader("purchase_id", ""+transID));
			
        Log.d("transID", "" + transID);
        
        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i("GET",response.getStatusLine().toString());
 
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release
 
            if (entity != null) {
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                Log.i("GET",result);
                
                // A Simple JSONObject Creation
                JSONObject json;
				json = new JSONObject(result);
				//JSONString merchant = json.getJSONString("")
				//String account = json.getString("account");
				String merchant = json.getString("account_name");
				JSONArray items = json.getJSONArray("items");
				ArrayList<PurchaseItem> purchaseItems = new ArrayList<PurchaseItem>(); 
				int date = items.getJSONObject(0).getInt("time");
				for (int i = 0; i < items.length(); i++) {
					JSONObject item = items.getJSONObject(i);
					PurchaseItem pi = new PurchaseItem(item.getString("title"), (float) item.getDouble("amount"));
					purchaseItems.add(pi);
				}
				
				instream.close();
				return new PurchaseEntity(merchant, purchaseItems, 0, "not here", date);
                //return result;
            }
 
 
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    
    public static boolean authenticateSwipe(String swipe) {
    	HttpClient httpclient = new DefaultHttpClient();
   	 
        // Prepare a request object
        HttpPost httppost = new HttpPost(authenticateUrl); 
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("swipe", swipe));
        try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 
        // Execute the request
		HttpResponse response;
		try {
			response = httpclient.execute(httppost);
			StatusLine sl = response.getStatusLine();
			if (sl != null && sl.getStatusCode() == 200) {
				Log.i("Rest", "authentication successful");
				return true;
			} else{
				Log.i("Rest", "authentication failure with status " + sl.getStatusCode());
				return false;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
    }
    
    public static boolean register (String phoneNumber, String deviceID, String swipe) {
    	
    	//XXX: check response
    	
    	HttpClient httpclient = new DefaultHttpClient();
      	 
        // Prepare a request object
        HttpPost httppost = new HttpPost(createUrl); 
        
        if (deviceID == null || swipe == null) {
        	Log.d("Rest", "registration info contains null. Return.");
        	return false;
        }
        if (phoneNumber == null) {
        	phoneNumber = new String("12068889999");
        }
        Log.d("Rest", "Register wth number " + phoneNumber);
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("phone", phoneNumber));
        nameValuePairs.add(new BasicNameValuePair("device", deviceID));
        nameValuePairs.add(new BasicNameValuePair("swipe", swipe));
        try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 
        // Execute the request
		HttpResponse response;
		try {
			response = httpclient.execute(httppost);
			StatusLine sl = response.getStatusLine();
			if (sl != null && sl.getStatusCode() == 200) {
				Log.i("Rest", "registration successful");
				return true;
			} else{
				Log.i("Rest", "registration failure with status " + sl.getStatusCode());
				return false;
			}
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
    }
    
    public static boolean transferMoney (String accountID, String phoneNumber, String amount) {
    	HttpClient httpclient = new DefaultHttpClient();
      	 
        // Prepare a request object
        HttpPost httppost = new HttpPost(mtomUrl); 
        
        if (accountID == null || amount == null) {
        	Log.d("Rest", "Account info contains null. Return.");
        	return false;
        }
        if (phoneNumber == null) {
        	phoneNumber = new String("12068889999");
        }
        Log.d("Rest", "Transfer to number " + phoneNumber + " from " + accountID + " " + amount);
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("phone", phoneNumber));
        nameValuePairs.add(new BasicNameValuePair("account_id", accountID));
        nameValuePairs.add(new BasicNameValuePair("amount", amount));
        try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 
        // Execute the request
		HttpResponse response;
		try {
			response = httpclient.execute(httppost);
			StatusLine sl = response.getStatusLine();
			if (sl != null && sl.getStatusCode() == 200) {
				Log.i("Rest", "Money transfer successful");
				return true;
			} else{
				Log.i("Rest", "Money transfer failure with status " + sl.getStatusCode());
				return false;
			}
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
    }
}
